package com.jason.concurrent.lockConditional;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author  yslai
 * @Date  2022/9/18 22:14
 * @Description 使用lock进行一个交替打印输出的并发编程
 */
class Share{

    private int number = 0;

    private Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    //增加一个加法的操作
    public void add() throws InterruptedException {
        try {
            lock.lock();
            while(number%2!=0)
            {
                //这里就进行一个等待的操作
                condition.await();
            }
            number++;
             //最后肯定要进行一个释放锁，且让唤醒其他的线程

            System.out.println(Thread.currentThread().getName()+"::"+number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    //增加一个减法的操作
    public void incr() throws InterruptedException {
        try {
            lock.lock();
            while(number%2!=1)
            {
                //这里就进行一个等待的操作
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"::"+number);
            condition.signalAll(); //最后肯定要进行一个释放锁，且让唤醒其他的线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    // 上锁
    // 判断通知

    //执行方法

    //解锁

    //通知其他对象获取锁

    // 进行资源的调用

}

public class LockTest {


    public static void main(String[] args) {

        Share share = new Share();

        Thread aa = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"aa");
        Thread bb = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"bb");
        Thread cc = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"cc");
        Thread dd = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"dd");
        aa.start();
        bb.start();
        cc.start();
        dd.start();

    }
}
